﻿using PhantomRealm.Common.Players;
using System.IO;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
using Terraria.ModLoader.IO;

namespace PhantomRealm.Common.Systems
{
    public class AuroraSystem : ModSystem
    {
        public const byte Default = byte.MaxValue;
        public static bool AuroraActive => AuroraType != Default;
        public static byte AuroraType { get; private set; } = Default;
        public override void Load() => TimeSystem.TimeChanged += UpdateAurora;

        private static void UpdateAurora(bool day)
        {
            if (Main.netMode != NetmodeID.MultiplayerClient)
            {
                AuroraType = Default;
                if (!day && Main.rand.NextBool(3))
                {
                    AuroraType = 1;
                }
            }
        }
        public override void ResetNearbyTileEffects()
        {
            Main.LocalPlayer.GetModPlayer<AuroraPlayer>().Reset();
        }
        public override void ClearWorld()
        {
            AuroraType = Default;
        }
        public override void NetSend(BinaryWriter writer)
        {
            writer.Write(AuroraType);
        }
        public override void NetReceive(BinaryReader reader)
        {
            AuroraType = reader.ReadByte();
        }
        public override void SaveWorldData(TagCompound tag)
        {
            tag[nameof(AuroraType)] = AuroraType;
        }
        public override void LoadWorldData(TagCompound tag)
        {
            AuroraType = tag.GetByte(nameof(AuroraType));
        }
    }
}
